#ifndef HEX_ENCODE_H_
#define HEX_ENCODE_H_

#include <iostream>
#include <fstream>
#include <stdint.h>
#include <iomanip>
#include <sstream>
#include <string>

class HexEncode {
private:
	const char* file_path;
public:
	HexEncode(const char* path) {
		this->file_path = path;
	}

	~HexEncode() {
	}

	//Guarda el contenido de un archivo en un string
	static string FileToString(const char* path) {
		ifstream ifs(path, ios::in | ios::binary);
				string buffer;
				int c = 0;
				while (ifs.good()) {
					c = ifs.get();
					if (ifs.good())
						buffer.push_back(c);

				}
				if(ifs.is_open())
				{
					ifs.close();
				}
				return buffer;
	}

	string Encode() {
		string buffer=FileToString(this->file_path);
		ostringstream ret;
		bool upper_case = true;
		//Conversion a hexadecimal
		for (string::size_type i = 0; i < buffer.length(); ++i) {
			int z = buffer[i] & 0xff;
			ret << std::hex << std::setfill('0') << std::setw(2)
					<< (upper_case ? std::uppercase : std::nouppercase) << z;
		}

		return ret.str();
	}

	int HexaDigitToBinary(char c) {
		int digit = -1;

		switch (c) {
		case '0':
			digit = 0;
			break;
		case '1':
			digit = 1;
			break;
		case '2':
			digit = 2;
			break;
		case '3':
			digit = 3;
			break;
		case '4':
			digit = 4;
			break;
		case '5':
			digit = 5;
			break;
		case '6':
			digit = 6;
			break;
		case '7':
			digit = 7;
			break;
		case '8':
			digit = 8;
			break;
		case '9':
			digit = 9;
			break;
		case 'A':
			digit = 10;
			break;
		case 'B':
			digit = 11;
			break;
		case 'C':
			digit = 12;
			break;
		case 'D':
			digit = 13;
			break;
		case 'E':
			digit = 14;
			break;
		case 'F':
			digit = 15;
			break;

		}
		return digit;
	}

	int HexByteToBinary(char c1, char c2) {
		return HexaDigitToBinary(c1) * 16 + HexaDigitToBinary(c2);
	}

	void Desencode(string* hexa_file) {
		FILE* fp=fopen(this->file_path,"wb");


		for (unsigned int i = 0; i < hexa_file->size() - 1; i = i + 2) {
			char c1, c2;
			c1 = hexa_file->at(i);
			c2 = hexa_file->at(i + 1);
			char byte = HexByteToBinary(c1, c2);

			fputc(byte,fp);

		}
		fclose(fp);
	}
};

#endif /* HEX_ENCODE_H_ */
